package util;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;

import models.MensagemMT;
import models.SiteConfig;
import siena.PersistenceManager;
import siena.PersistenceManagerFactory;
import siena.gae.GaePersistenceManager;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class HumanSMSUtil extends SMSUtil {
	private SiteConfig siteConfig;

	HumanSMSUtil() {
		super();
	}

	@Override
	public HTTPResponse send() throws Exception {
		URLFetchService urlFetchService = URLFetchServiceFactory
				.getURLFetchService();
		HTTPRequest httpRequest = new HTTPRequest(new URL(
				"http://system.human.com.br/GatewayIntegration/msgSms.do"),
				HTTPMethod.POST);

		byte[] payload = getPayload().getBytes("ISO-8859-1");

		httpRequest.addHeader(new HTTPHeader("Content-Type",
				"application/x-www-form-urlencoded"));
		httpRequest.addHeader(new HTTPHeader("Content-Length", ""
				+ payload.length));

		httpRequest.setPayload(payload);

		return urlFetchService.fetch(httpRequest);
	}

	@Override
	protected String getPayload() {
		MensagemMT mensagemMT = new MensagemMT();

		mensagemMT.setContent(text);
		mensagemMT.setDestination(destination);

		mensagemMT.insert();

		Map<String, String> propertyMap = new TreeMap<String, String>();

		String accountId = siteConfig.getConfig("sms.broker.user");
		String accountCode = siteConfig.getConfig("sms.broker.password");

		propertyMap.put("account", accountId);
		propertyMap.put("code", accountCode);

		propertyMap.put("dispatch", "send");
		propertyMap.put("msg", text);
		propertyMap.put("to", getFormattedDestination());
		propertyMap.put("id", "" + mensagemMT.getOid());

		return getEncodedPayload(propertyMap);
	}

	private String getFormattedDestination() {
		String result = destination.replaceFirst("\\+", "");

		result = result.trim();

		return result;
	}

	private String getEncodedPayload(Map<String, String> propertyMap) {
		StringBuilder stringBuilder = new StringBuilder();

		{
			int i = 0;

			for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
				if (0 != i)
					stringBuilder.append("&");

				stringBuilder.append(entry.getKey()).append('=').append(
						getValue(entry.getValue()));

				i++;
			}
		}

		String payload = stringBuilder.toString();
		return payload;
	}

	private String getValue(String value) {
		try {
			return URLEncoder.encode(value, "latin1");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	protected void loadConfig() {
		siteConfig = SiteConfig.load();
	}

	public static void main(String[] args) throws Exception {
		PersistenceManager persistenceManager = new GaePersistenceManager();

		persistenceManager.init(null);

		PersistenceManagerFactory.install(persistenceManager, MensagemMT.class);

		SMSUtil smsObject = SMSUtil.create(HumanSMSUtil.class).setText(
				"Teste de Mensagem com Acentuação - Conteúdo da Mensagem")
				.setDestination("+559184253266");

		HTTPResponse httpResponse = smsObject.send();

		for (HTTPHeader header : httpResponse.getHeaders())
			writeln("header['%s']: %s\n", header.getName(), header.getValue());

		writeln("result: " + new String(httpResponse.getContent()));
	}

	private static void writeln(String pattern, String... args) {
		if (args.length == 0) {
			System.out.println(pattern);
		} else {
			String result = String.format(pattern, (Object[]) args);

			System.out.println(result);
		}
	}
}
